package com.guangwei.oahelp.zwt;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class QueryTrainTicket {

	public static void main(String[] args) throws Exception {
		//访问12306查火车票
		
		Scanner in = new Scanner(System.in);
		System.out.println("起点站");
		String startCity = in.next();
		System.out.println("终点站");
		String endCity = in.next();
		System.out.println("出发日期(2016-06-06)");
		String goData = in.next();
		String path = System.getProperty("user.dir")+"\\bin\\station_name.txt";
		StringBuilder sb = readTxtFile(path);
		String[] stations = sb.toString().split("@");
		List<String> startList = new ArrayList<String>();
		List<String> endList = new ArrayList<String>();
		for(int i=1;i<stations.length;i++){
			String station[] = stations[i].replace("|", ",").split(",");
			if(station[1].indexOf(startCity)>-1){
				startList.add(station[2]);
			}
			if(station[1].indexOf(endCity)>-1){
				endList.add(station[2]);
			}
		}
		
		printTicketInfo(getTicketInfo(startList.get(0), endList.get(0), goData));
	}
	
	
	public static StringBuilder readTxtFile(String filePath){
		StringBuilder sb = new StringBuilder();
        try {
                String encoding="GBK";
                File file=new File(filePath);
                if(file.isFile() && file.exists()){ //判断文件是否存在
                    InputStreamReader read = new InputStreamReader(new FileInputStream(file),encoding);//考虑到编码格式
                    BufferedReader bufferedReader = new BufferedReader(read);
                    String lineTxt = null;
                    while((lineTxt = bufferedReader.readLine()) != null){
                        sb.append(lineTxt);
                    }
                    read.close();
        }else{
            System.out.println("找不到指定的文件");
        }
        } catch (Exception e) {
            System.out.println("读取文件内容出错");
            e.printStackTrace();
        }
        return sb;
    }
	
	//从12306获取火车票信息并返回JSONArray
	public static JSONArray getTicketInfo(String startCity, String endCity,
			String goDate) throws Exception {
		//安全证书认证
		TrustManager[] tm = { new MyX509TrustManager() };
		SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
		sslContext.init(null, tm, new java.security.SecureRandom());

		// 从上述SSLContext对象中得到SSLSocketFactory对象
		SSLSocketFactory ssf = sslContext.getSocketFactory();

		String urlStr = "https://kyfw.12306.cn/otn/lcxxcx/query?purpose_codes=ADULT&queryDate="
				+ goDate
				+ "&from_station="
				+ startCity
				+ "&to_station="
				+ endCity;

		URL url = new URL(urlStr);

		HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
		con.setSSLSocketFactory(ssf);

		InputStreamReader in = new InputStreamReader(con.getInputStream(),
				"utf-8");

		BufferedReader bfreader = new BufferedReader(in);

		StringBuffer sb = new StringBuffer();

		String line = "";

		while ((line = bfreader.readLine()) != null) {
			sb.append(line);
		}
		String ticketInfo = sb.toString();
		JSONObject obj = JSONObject.fromObject(ticketInfo);
		JSONObject data = obj.getJSONObject("data");
		JSONArray datas = data.getJSONArray("datas");
		return datas;
	}

	public static void printTicketInfo(JSONArray datas){
		
		if(datas.size()>0&&datas!=null){
			for (int i = 0; i < datas.size(); i++) {
				JSONObject obj1 = datas.getJSONObject(i);
				System.out.print("车次：" + obj1.getString("station_train_code")+"   ");
//				System.out.print("始发站：" + obj1.getString("start_station_name")+"   ");
//				System.out.print("终点站：" + obj1.getString("end_station_name")+"   ");
				System.out.print("出发站：" + obj1.getString("from_station_name")+"   ");
				System.out.print("目的站：" + obj1.getString("to_station_name")+"   ");
				System.out.print("出发时间：" + obj1.getString("start_time")+"   ");
				System.out.print("到达时间：" + obj1.getString("arrive_time")+"   ");
				System.out.print("历时：" + obj1.getString("lishi")+"   ");
				String type = obj1.getString("station_train_code");
				if (type.indexOf("Z") > -1) {
					System.out.print("软卧：" + obj1.getString("rw_num")+"   ");
					System.out.print("硬卧：" + obj1.getString("yw_num")+"   ");
				} else if (type.indexOf("D") > -1) {
					System.out.print("一等座：" + obj1.getString("zy_num")+"   ");
					System.out.print("二等座：" + obj1.getString("ze_num")+"   ");
					System.out.print("无座：" + obj1.getString("wz_num")+"   ");
				} else if (type.indexOf("K") > -1) {
					System.out.print("软卧：" + obj1.getString("rw_num")+"   ");
					System.out.print("硬卧：" + obj1.getString("yw_num")+"   ");
					System.out.print("硬座：" + obj1.getString("yz_num")+"   ");
					System.out.print("无座：" + obj1.getString("wz_num")+"   ");
				} else if (type.indexOf("G") > -1) {
					System.out.print("商务座：" + obj1.getString("swz_num")+"   ");
					System.out.print("一等座：" + obj1.getString("zy_num")+"   ");
					System.out.print("二等座：" + obj1.getString("ze_num")+"   ");
				} else if (type.indexOf("T") > -1) {
					System.out.print("软卧：" + obj1.getString("rw_num")+"   ");
					System.out.print("硬卧：" + obj1.getString("yw_num")+"   ");
					System.out.print("硬座：" + obj1.getString("yz_num")+"   ");
					System.out.print("无座：" + obj1.getString("wz_num")+"   ");
				} else if (type.indexOf("C") > -1) {
					System.out.print("一等座：" + obj1.getString("zy_num")+"   ");
					System.out.print("二等座：" + obj1.getString("ze_num")+"   ");
					System.out.print("无座：" + obj1.getString("wz_num")+"   ");
				}
				System.out.println("备注：" + obj1.getString("note")+"   ");
				System.out.println("--------------------------------------------------------------------------------------------------------------------------------------");
			}
			System.out.println("共有"+datas.size()+"个车次!");
		}
	}
	
}
